package com.cloudlinkscm.loms.services.base.notify.domain.notifier.dispatcher;

import com.cloudlinkscm.loms.services.base.notify.constant.SendStatusEnum;
import com.cloudlinkscm.loms.services.base.notify.domain.notifier.Dispatcher;
import com.cloudlinkscm.loms.services.base.notify.dto.email.Cc;
import com.cloudlinkscm.loms.services.base.notify.model.EmailNotification;
import com.cloudlinkscm.loms.services.base.notify.model.EmailNotificationResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author : tac
 * @date : 2017/6/16
 */

@Component
public class EmailNotificationDispatcher implements Dispatcher<EmailNotification,EmailNotificationResult> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 执行发送
     *
     * @see #setSMTP(EmailNotification, HtmlEmail)
     * @see #setMailInfo(EmailNotification, HtmlEmail)
     */
    @Override
    public EmailNotificationResult dispatch(EmailNotification notification) {
        EmailNotificationResult result = new EmailNotificationResult();

        try {
            HtmlEmail email = new HtmlEmail();
            setSMTP(notification, email);
            setMailInfo(notification, email);
            email.setCharset("UTF-8");
            email.send();
        } catch (EmailException e) {
            logger.error("邮件发送失败", e);
            result.setState(SendStatusEnum.FAILURE.val);
            result.setErrorMsg(e.getMessage());
            return result;
        }

        result.setState(SendStatusEnum.SENT.val);
        result.setErrorMsg("邮件发送成功");
        return result;
    }


    /**
     * 设置邮件发送的SMTP服务器相关信息
     *
     * @throws EmailException
     */
    private void setSMTP(EmailNotification notification, HtmlEmail email) throws EmailException {
        email.setHostName(notification.getHostName());
        email.setSmtpPort(notification.getPort());
        email.setSSLOnConnect(notification.getSsl());
        email.setAuthentication(notification.getAccount(), notification.getPassword());
        email.setFrom(notification.getAccount() + "@" + notification.getSuffix());
    }

    /**
     * 设置与邮件本身相关的信息
     *
     * @throws EmailException
     */
    private void setMailInfo(EmailNotification notification, HtmlEmail email) throws EmailException {
        email.setSubject(notification.getSubject());
        email.setMsg(notification.getMsg());
        email.addTo(notification.getRecipient());
        if(!CollectionUtils.isEmpty(notification.getCcls())){
            for (Cc cc : notification.getCcls()){
                email.addCc(cc.getMail());
            }
        }
    }
}
